package com.xuanwu.shop.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.xuanwu.shop.dao.GoodsDaoInterface;
import com.xuanwu.shop.entity.Category;
import com.xuanwu.shop.entity.Goods;
import com.xuanwu.shop.entity.GoodsStatus;

public class GoodsDaoImpl extends BaseDao implements GoodsDaoInterface {

	@Override
	public List<Goods> findByCatId(int catId) {
		String sql = "select id,name,picture,price,number,staid from book where cateid=?";
		List<Goods> list = null;
		Goods goods = null;
		try {
			conn = getConnection();
			psta = conn.prepareStatement(sql);
			psta.setInt(1, catId);
			rs = psta.executeQuery();
			while(rs.next()){
				if(list == null){
					list = new ArrayList<>();
				}
				goods = new Goods();
				goods.setId(rs.getString(1));
				goods.setName(rs.getString(2));
				goods.setPic(rs.getString(3));
				goods.setPrice(rs.getDouble(4));
				goods.setNumber(rs.getInt(5));
				GoodsStatus status = new GoodsStatus();
				status.setId(rs.getInt(6));
				goods.setGoodsStatus(status);
				Category category = new Category();
				category.setId(catId);
				goods.setCategory(category);
				list.add(goods);
			}
			close(conn, psta, rs);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public Goods findById(String id) {
		String sql = "select name,picture,price,number,staid,cateid from book where id=?";
		Goods goods = null;
		try {
			conn = getConnection();
			psta = conn.prepareStatement(sql);
			psta.setString(1, id);
			rs = psta.executeQuery();
			if(rs.next()){
				goods = new Goods();
				goods.setId(id);
				goods.setName(rs.getString(1));
				goods.setPic(rs.getString(2));
				goods.setPrice(rs.getDouble(3));
				goods.setNumber(rs.getInt(4));
				GoodsStatus status = new GoodsStatus();
				status.setId(rs.getInt(5));
				Category category = new Category();
				category.setId(rs.getInt(6));
				goods.setCategory(category);
				goods.setGoodsStatus(status);
			}
			close(conn, psta, rs);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return goods;
	}

}
